package com.cloud.platform.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileUtil {

	/**
	 * copy single file
	 * 
	 * @param srcFile
	 * @param destFile
	 * @throws IOException
	 */
	public static void copyFile(String srcFileAddr, String destFileAddr) throws IOException {
		
		File srcFile = new File(srcFileAddr);
		File destFile = new File(destFileAddr);
		
		// check source and dest file if is exist
		if(!srcFile.exists() || destFile.exists()) {
			return;
		}
		
		// check dest file dir if is exist, if not, create dest dir
		String destAddress = destFile.getAbsolutePath();
		String destDir = destAddress.substring(0, destAddress.lastIndexOf(File.separator));
		
		File dir = new File(destDir);
		
		if(!dir.exists()) {
			dir.mkdirs();
		}
		
		FileChannel fin = null;
		FileChannel fos = null;
		
		try {
			// init input and output channel
			fin = new FileInputStream(srcFile).getChannel();
			fos = new FileOutputStream(destFile).getChannel();
			
			// init nio buffer
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			
			while(true) {
				// clear buffer first
				buffer.clear();
				
				// put input file datas to buffer
				int r = fin.read(buffer);
				
				// read complete
				if(r == -1) {
					break;
				}
				
				// convert buffer from write mode to read mode
				buffer.flip();
				
				// write buffer datas to output file
				fos.write(buffer);
			}
			
		} finally {
			// make sure close stream
			if(fin != null) {
				fin.close();
			}
			if(fos != null) {
				fos.close();
			}
		}
	}
	
	/**
	 * ===============================  Test  ===============================
	 */
	public static void main(String[] args) {
		
		try {
			copyFile("E:\\test1.txt", "E:\\test2.txt");
			
		} catch(Exception e) {}
	}
}
